package utils

import java.sql.Timestamp
import java.util.Date

import io.circe.{ Decoder, Encoder }
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat

import scala.util.Try

trait CirceUtils {

  def timestampEncoderFromPattern(pattern: String): Encoder[Timestamp] = {
    Encoder.encodeString.contramap { time =>
      new DateTime(time.getTime).toString(pattern)
    }
  }

  def timestampDeocderFromPattern(pattern: String): Decoder[Timestamp] = {
    val format = DateTimeFormat.forPattern(pattern)
    Decoder.decodeString.emapTry { str =>
      Try {
        new Timestamp(format.parseDateTime(str).getMillis)
      }
    }
  }

  def sqlDateEncoderFromPattern(pattern: String): Encoder[Date] = {
    Encoder.encodeString.contramap { time =>
      new DateTime(time.getTime).toString(pattern)
    }
  }

  def sqlDateDecoderFromPattern(pattern: String): Decoder[Date] = {
    val format = DateTimeFormat.forPattern(pattern)
    Decoder.decodeString.emapTry { str =>
      Try {
        new Date(format.parseDateTime(str).getMillis)
      }
    }
  }

}
